<?php

namespace Registration\Model;

use Registration\Model\Position;

use Zend\Db\TableGateway\TableGateway;

class PositionTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll() {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function getPosition($id) {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function getStatus($id) {
        $id = (int) $id;
        $select = $this->tableGateway->getSql()->select();
        $select->columns(array('status'));
        $select->where(array('id' => $id));
        $rowset = $this->tableGateway->selectWith($select);

//        $rowset = $this->tableGateway->select(
//                function (Select $select) {
//                    $select->where->like('name', 'Brit%');
//                    $select->order('name ASC')->limit(2);
//                });

        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }

        return $row;
    }

    public function savePosition(Position $Positions) {
        $data = array('id' => $Positions->id,
            'mere_id' => $Positions->mere_id,
            'name' => $Positions->name,
            'price' => $Positions->price,
            'status' => $Positions->status,
            'comments' => $Positions->comments
        );


        $id = (int) $Positions->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getPosition($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }

    public function deletePosition($id) {
        $this->tableGateway->delete(array('id' => $id));
    }

}